﻿using AutoMapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Tauren.Business.DLL.LogIn;
using Tauren.Business.DLL.TenantInformation;
using Tauren.Business.Entity.Config;
using Tauren.Business.Entity.Enum;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Input;
using Tauren.Business.Entity.Model;
using Tauren.Business.Infrastructure.Common;

namespace Tauren.Business.Service.LogIns
{
    public class LogInService : ILogInService
    {
        private IMapper mapper { get; set; }
        public ITenantInformationBusiness tBusiness { get; set; }
        public LogInService(IMapper _mapper)
        {
            mapper = _mapper;
        }
        /// <summary>
        /// 进行登录
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        public IResponseMessage LogIn(LogInModel User)
        {
            if (string.IsNullOrWhiteSpace(User.Content) || User.Content == "string" || string.IsNullOrWhiteSpace(User.Key) || User.Key == "string")
            {
                return ErrorType.BUSINESS_LOGIN_SECRET_ERROR.Failure(ErrorMessage.BUSINESS_LOGIN_SECRET_ERROR);
            }
            string UserInfo = User.Content.AESDecrypt(User.Key);
            LogInUser logInUser = UserInfo.ToEntity<LogInUser>();
            if (null == logInUser)
            {
                return ErrorType.BUSINESS_NOT_FOUND_LOGIN.Failure(ErrorMessage.BUSINESS_NOT_FOUND_LOGIN);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(logInUser.Account) || logInUser.Account == "string")
                {
                    return ErrorType.BUSINESS_EMPTY_LOGIN_ACCOUNT.Failure(ErrorMessage.BUSINESS_EMPTY_LOGIN_ACCOUNT);
                }
                else if (string.IsNullOrWhiteSpace(logInUser.Password) || logInUser.Password == "string")
                {
                    return ErrorType.BUSINESS_EMPTY_LOGIN_PASSWORD.Failure(ErrorMessage.BUSINESS_EMPTY_LOGIN_PASSWORD);
                }
                else
                {

                    Entity.Model.TenantInformation tenantInformation = tBusiness.GetByCode(User.TenantCode);
                    if (tenantInformation == null)
                        return ErrorType.BUSINESS_NOT_TENANTINFO.Failure(ErrorMessage.BUSINESS_NOT_TENANTINFO);
                    ///获取数据库连接
                    IDbConnection ChildConnection = new MySqlConnection(tenantInformation.dbConnection);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        ILogInBusiness business = new LogInBusiness(ChildConnection);
                        Entity.Model.AccoutInfo accoutInfo = business.GetAccoutInfo(logInUser.Account);
                        ///判断是否有登录账号的信息
                        if (accoutInfo is null)
                            return ErrorType.BUSINESS_EMPTY_NOTFOUND_ACCOUNTINFO.Failure(ErrorMessage.BUSINESS_EMPTY_NOTFOUND_ACCOUNTINFO);
                        ///判断密码是否正确
                        if (accoutInfo.Password != logInUser.Password)
                            return ErrorType.BUSINESS_EMPTY_LOGIN_PASSWORD_ERROR.Failure(ErrorMessage.BUSINESS_EMPTY_LOGIN_PASSWORD_ERROR);
                        Entity.Model.Employee employee = business.GetEmployeeInfo(accoutInfo.EmpId);
                        if (employee is null)
                            return ErrorType.BUSINESS_EMPTY_NOTFOUND_EMPLOYEEINFO.Failure(ErrorMessage.BUSINESS_EMPTY_NOTFOUND_EMPLOYEEINFO);
                        bool IsAdmin = business.IsCurrentRoleByAdmin(employee.EmpId);
                        GlobalModel globalModel = BuildGlobalModel(tenantInformation, accoutInfo, employee, IsAdmin, business.GetOrganizationInfo(int.Parse(employee.OrgId)), business.GetPositionInfo(int.Parse(employee.PositionId)));
                        var token = new TokenBusiness().GenerateToken(accoutInfo.Account, accoutInfo.Name, globalModel.ToJsonString()).Result;
                        if (null != token)
                        {
                            token.language = accoutInfo.Language;
                            return token.Succeed(Code: ErrorType.BUSINESS_LOGIN_SUCCESSED, message: ErrorMessage.BUSINESS_LOGIN_SUCCESSED);
                        }
                        else
                        {
                            return ErrorType.BUSINESS_EMPTY_LOGIN_TOKEN_ERROR.Failure(ErrorMessage.BUSINESS_EMPTY_LOGIN_TOKEN_ERROR);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 创建缓存信息
        /// </summary>
        /// <returns></returns>
        public GlobalModel BuildGlobalModel(Entity.Model.TenantInformation tenant, Entity.Model.AccoutInfo accoutInfo, Entity.Model.Employee employee, bool isAdmin, Entity.Model.Organization organization, Entity.Model.Position position)
        {
            return new GlobalModel()
            {
                Account = accoutInfo.Account,
                EmpEnName = employee.ENName,
                EmpId = employee.EmpId,
                EmpName = employee.CNName,
                FileConnection = tenant.files_Dbconnection,
                FlowConnection = tenant.wf_dbConnection,
                FormConnection = tenant.wf_form_Dbconnection,
                BasicDataConnection = tenant.dbConnection,
                ResConnection = tenant.Res_Dbconnection,
                IsAdmin = isAdmin,
                Language = accoutInfo.Language,
                TenementCode = tenant.Code,
                UserId = accoutInfo.AutoId,
                OrgId = int.Parse(employee.OrgId),
                PositionId = int.Parse(employee.PositionId),
                TenementName = tenant.CNName,
                TenementPhone = tenant.Phone,
                OrgName = accoutInfo.Language == "zh-cn" ? organization?.CNName : organization?.ENName,
                PositionName = accoutInfo.Language == "zh-cn" ? position?.CNName : position?.ENName,
                EmpCode = employee.EmpCode
            };
        }
    }
}
